import Phone from "@/components/Phone";
import router from "@/router";
import vueRouter from "@/router";
import { useRouter } from "vue-router";
import * as vant from "vant";
import moment from "moment";
const { showFailToast } = vant;

// 跳转到登录
export const jumpLogin = function jumpLogin() {
  vueRouter.push({ path: "/login" });
};

// 获取尺寸
export const getSize = function getSize(size: number) {
  if (size == 0) return 0;
  return size / 3.75 + "vw";
};

// 判断是否是微信
export const isWechat = function () {
  let ua = navigator.userAgent.toLowerCase();
  let isWeixin = ua.indexOf("micromessenger") != -1;
  // console.log(navigator.userAgent, '判断当前浏览器是什么内核', isWeixin)
  if (isWeixin) {
    return true;
  } else {
    return false;
  }
};

// 获取地理位置
export const getPosition = function () {
  // return new Promise((resolve, reject) => {
  const errorResolve = () =>
    localStorage.setItem(
      "positionData",
      JSON.stringify({
        latitude: "29.80",
        longitude: "121.55",
      })
    );
  if (navigator.geolocation) {
    try {
      // 获取当前位置信息
      navigator.geolocation.getCurrentPosition(
        function (position) {
          console.log(
            "定位成功：",
            position.coords.latitude,
            position.coords.longitude,
            position.coords
          );
          localStorage.setItem(
            "positionData",
            JSON.stringify({
              latitude: position.coords.latitude.toFixed(6),
              longitude: position.coords.longitude.toFixed(6),
            })
          );
        },
        function (error) {
          console.log("定位失败：", error);
          errorResolve();
        }
      );
    } catch (error: any) {
      console.log("getCurrentPosition 方法执行失败：", error.message);
      errorResolve();
    }
  } else {
    console.log("浏览器不支持 Geolocation API");
    errorResolve();
  }
  // AMap.plugin("AMap.Geolocation", () => {
  //   let geolocation = new AMap.Geolocation({
  //     enableHighAccuracy: false, // 是否使用高精度定位，默认:true
  //     timeout: 10000, // 超过10秒后停止定位，默认：无穷大
  //     maximumAge: 60000, // 定位结果缓存0毫秒，默认：0
  //     convert: true, // 自动偏移坐标，偏移后的坐标为高德坐标，默认：true
  //     showButton: true, // 显示定位按钮，默认：true
  //     buttonPosition: "LB", // 定位按钮停靠位置，默认：'LB'，左下角
  //     buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
  //     showMarker: true, // 定位成功后在定位到的位置显示点标记，默认：true
  //     showCircle: true, // 定位成功后用圆圈表示定位精度范围，默认：true
  //     panToLocation: true, // 定位成功后将定位到的位置作为地图中心点，默认：true
  //     zoomToAccuracy: true, // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
  //   });
  //   geolocation.getCurrentPosition();
  //   AMap.Event.addListener(
  //     geolocation,
  //     "complete",
  //     (data: { position: { latitude: any; longitude: any } }) => {
  //       console.log("resolve", data);
  //       resolve(data.position);
  //     }
  //   );
  //   AMap.Event.addListener(geolocation, "error", (data: {}) => {
  //     console.log("reject", data);
  //     // resolve({})
  //     reject(data);
  //   });
  // });
  // });
};

export const getBackGroundColor = () => {
  return "linear-gradient(152deg, #F9E7E3 0%, #F7F6F7 41%, #F6F6F6 100%)";
};
export interface IUserType {
  // 大户
  dh?: string;
  // 小户
  xh?: string;
}

export const getUserTypeValue = () => {
  const userInfo = localStorage.getItem("userInfo") as string;
  const userInfoJSON = JSON.parse(userInfo) as { userType: string };
  let type = userInfoJSON
    ? ["dh", "xh"][Number(userInfoJSON.userType) - 1]
    : "dh";
  return type;
};

export const getUserInfoUrl = (urlParams: any, params?: any) => {
  if (params) {
    console.log("getUserTypeValue", getUserTypeValue());
    return {
      url: urlParams[getUserTypeValue()],
      params,
    };
  } else {
    return {
      url: urlParams[getUserTypeValue()],
      params: {},
    };
  }
};

export const getUserType = () => {
  return getUserTypeValue() == "dh" ? "1" : "2";
};

export const isDh = () => {
  return getUserTypeValue() == "dh" ? true : false;
};

// 滚动到指定为止
export const scrollToPosition = (y: number) => {
  document.getElementById("page-body")!.scrollTop = y;
};

//打电话
export const phoneClick = (e: any) => {
  if (e) {
    location.href = "tel://" + e;
  }
};

//电话加*******
export const phoneNumControl = (e: any) => {
  const num = e ? String(e) : "";
  return num.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
};

export const routerClick = (e: any, info: any) => {
  const routerDom = useRouter();
  console.log("------------", info);
  info ? routerDom.push({ path: e, query: info }) : routerDom.push({ path: e });
};

export const urlParams = new URLSearchParams(
  window.location.href.split("?")[1]
);

export const formDataControl = (data: any) => {
  const { result, error } = data;
  if (Object.keys(error).length === 0) {
    return { result, error, submitState: true };
  } else {
    const firstValue = error[Object.keys(error)[0]];
    showFailToast(firstValue);
    return { result: {}, error, submitState: false };
  }
};

// 判断两个时间格式为00:00 的时间判断
export const getTimeRules = (startT: any, endT: any) => {
  const startTime = moment(`1970-01-01T${startT}:00`);
  const endTime = moment(`1970-01-01T${endT}:00`);
  if (startTime.isAfter(endTime)) {
    return true;
  } else if (startTime.isSame(endTime)) {
    return true;
  } else {
    return false;
  }
};

export default {
  jumpLogin,
  getSize,
  isWechat,
  getPosition,
  getBackGroundColor,
  getUserInfoUrl,
  getUserTypeValue,
  isDh,
  getUserType,
  scrollToPosition,
  phoneClick,
  urlParams,
  routerClick,
  formDataControl,
  getTimeRules,
};
